<template>
  <div class="dashboard-container" style="background-color: #f0f2f5;height: 810px;">
    <!-- github角标 -->
    <github-corner class="github-corner" />
    <!-- 添加额外的间距 -->
    <div style="margin-top: 55px;"></div>
    <!-- 数据卡片 -->
    <el-row :gutter="10" class="mt-3">
      <el-col
        :xs="24"
        :sm="12"
        :lg="6"
        v-for="(item, index) in cardData"
        :key="index"
      >
        <el-card shadow="never" style="height: 180px; padding: 0;">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-[var(--el-text-color-secondary)]">{{
                item.title
              }}</span>
              <el-tag :type="item.tagType">
                {{ item.tagText }}
              </el-tag>
            </div>
          </template>

          <div class="flex items-center justify-between mt-5">
            <!-- <div class="text-right" style="font-size: 45px; font-weight: bold; color: #1bc23d; text-align: center;">
                {{ item.count }}
            </div> -->
  <div
    class="text-right"
    :style="countStyle(item.count)"
    style="font-weight: bold; color: #1bc23d; text-align: center;">
      <span v-for="(char, index) in formattedCount(item.count)" :key="index" :style="charStyle(index, item.count)">
        {{ char }}
      </span>
  </div>

            <svg-icon :icon-class="item.iconClass" size="2em" />
          </div>
          <div
            class="flex items-center justify-between mt-5 text-sm text-[var(--el-text-color-secondary)]"
          >
          <span style="font-size: 12px; color: gray;"> {{ item.dataDesc }} </span>

            <!-- <span> {{ Math.round(item.count * 15) }} </span> -->
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加额外的间距 -->
    <div style="margin-top: 55px;"></div>
    <!-- Echarts 图表 -->
    <el-row :gutter="10" class="mt-3" style="display: flex; justify-content: center;">
      <el-col
        :xs="24"
        :sm="12"
        :lg="8"
        class="mb-2"
        style="margin-left: 40px; margin-right: 40px;" 
        v-for="item in chartData"
        :key="item"
      >
        <component
          :is="chartComponent(item)"
          :id="item"
          height="400px"
          width="100%"
          class="bg-[var(--el-bg-color-overlay)]"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import type { EpPropMergeType } from "element-plus/es/utils/vue/props/types";
import axios from 'axios'; // 引入axios用于发起HTTP请求
axios.defaults.baseURL = 'http://127.0.0.1:8080';


// 定义一个计算属性来处理字体大小
const countStyle = (count) => {
  // 将数字转换为字符串
  const countStr = count.toString();
  // 检查字符串长度是否大于或等于6
  if (countStr.length >= 6) {
    // 如果第六个字符存在，则返回一个样式对象，使第一个和第六个字符的字体大小更大
    return {
      'font-size': 'calc(45px * 1.2)',
      'font-weight': 'bold'
    };
  } else {
    // 如果第六个字符不存在，则返回一个样式对象，使所有字符的字体大小保持一致
    return {
      'font-size': '45px',
      'font-weight': 'bold'
    };
  }
};

// 定义一个函数来格式化计数
const formattedCount = (count) => {
  return count.toString().split(''); // 将计数转换为数组
};

// 定义一个函数来根据索引返回字符样式
const charStyle = (index, count) => {
  const countStr = count.toString();
  const countArray = formattedCount(count);

  // 如果字符长度为9，那么第一个字符和第六个字符字体大小一致（45px）
  if (countStr.length === 9) {
    if (index === 0 || index === 5) {
      return {
        'font-size': '45px',
        'font-weight': 'bold'
      };
    }else{
      return {
        'font-size': '25px',
        // 'font-weight': 'bold'
      };
  }
  }
  // 如果字符长度为11，那么第一个、第二个、第七个和第八个字符字体大小一致（45px）
  else if (countStr.length === 11) {
    if (index === 0 || index === 1 || index === 6 || index === 7) {
      return {
        'font-size': '45px',
        'font-weight': 'bold'
      };
    }else{
      return {
        'font-size': '25px',
        // 'font-weight': 'bold'
      };
  }}
  // 如果字符长度既不是9也不是11，所有字符字体大小一致（45px）
  return {
    'font-size': '45px',
    'font-weight': 'bold'
  };
};

interface CardProp {
  title: string;
  tagType: EpPropMergeType<
    StringConstructor,
    "primary" | "success" | "info" | "warning" | "danger",
    unknown
  >;
  tagText: string;
  count: any;
  dataDesc: string;
  iconClass: string;
}

defineOptions({
  name: "Dashboard",
  inheritAttrs: false,
});

// import { useUserStore } from "@/store/modules/user";
import { useTransition, TransitionPresets } from "@vueuse/core";

import { ref } from 'vue';
import { defineAsyncComponent } from 'vue'; 
import { onMounted } from 'vue';

// const userStore = useUserStore();
const date: Date = new Date();


const duration = 5000;

// 登录人次（上一日）
const amount = ref(0);
const fetchDailyLoginCount = async () => {
  try {
    const response = await axios.get('/back/record/getSumCount/');
    amount.value = response.data;
  } catch (error) {
    console.error("Error fetching daily login count:", error);
  }
};

// 登录人次（上一周）
const weekamount = ref(0);
const fetchWeeklyLoginCount = async () => {
  try {
    const response = await axios.get('/back/record/get_last_week_dates/');
    weekamount.value = response.data;
  } catch (error) {
    console.error("Error fetching weekly login count:", error);
  }
};

// 常用时段（一日）
const daytime = ref("");
const fetchDaylyCommonTime = async () => {
  try {
    const response = await axios.get('/back/record/getDayAverageLogin/');
    daytime.value = mapDataToTimePeriod(response.data);
    console.log(response.data); // 添加调试信息
  } catch (error) {
    console.error("Error fetching dayly common time:", error);
  }
};

// 常用时段（一周）
const weektime = ref("");
const fetchWeeklyCommonTime = async () => {
  try {
    const response = await axios.get('/back/record/getAverageLogin/');
    weektime.value = mapDataToTimePeriod(response.data);
    console.log(response.data); // 添加调试信息
  } catch (error) {
    console.error("Error fetching weekly common time:", error);
  }
};

// 数据映射到时间段
const mapDataToTimePeriod = (data) => {
  switch (data) {
    case 0: return "0:00-2:00";
    case 2: return "2:00-4:00";
    case 4: return "4:00-6:00";
    case 6: return "6:00-8:00";
    case 8: return "8:00-10:00";
    case 10: return "10:00-12:00";
    case 12: return "12:00-14:00";
    case 14: return "14:00-16:00";
    case 16: return "16:00-18:00";
    case 18: return "18:00-20:00";
    case 20: return "20:00-22:00";
    case 22: return "22:00-24:00";
    default: return "";
  }
};
interface CardProp {
  title: string;
  tagType: EpPropMergeType<
    StringConstructor,
    "primary" | "success" | "info" | "warning" | "danger",
    unknown
  >;
  tagText: string;
  count: any; // 使用联合类型来支持数字和字符串
  dataDesc: string;
  iconClass: string;
}
// 卡片数量
const cardData = ref<CardProp[]>([
  {
    title: "登录人次",
    tagType: "success",
    tagText: "日",
    count: amount,
    dataDesc: "上一日总登录人次",
    iconClass: "Plus",
  },
  {
    title: "常用时段",
    tagType: "primary",
    tagText: "日",
    count: daytime, // 使用转换后的值
    dataDesc: "上一日常用时段",
    iconClass: "daytime",
  },
  {
    title: "登录人次",
    tagType: "success",
    tagText: "周",
    count: weekamount,
    dataDesc: "上一周总登录人次",
    iconClass: "weekamount",
  },
  {
    title: "常用时段",
    tagType: "danger",
    tagText: "周",
    count: weektime, // 使用转换后的值
    dataDesc: "上一周常用时段",
    iconClass: "time",
  },
]);
// 图表数据
const chartData = ref(["BarChart", "PieChart"]);
const chartComponent = (item: string) => {
  return defineAsyncComponent(() => import(`./components/${item}.vue`));
};

// 在组件挂载后获取数据
onMounted(async () => {
  await fetchDailyLoginCount();
  await fetchWeeklyLoginCount();
  await fetchDaylyCommonTime();
  await fetchWeeklyCommonTime();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  padding: 24px;

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }

  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .data-box {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    font-weight: bold;
    color: var(--el-text-color-regular);
    background: var(--el-bg-color-overlay);
    border-color: var(--el-border-color);
    box-shadow: var(--el-box-shadow-dark);
  }

  .svg-icon {
    fill: currentcolor !important;
  }
}


</style>